<template>
  <view class="team-member-selector">
    <!-- 选择按钮 -->
    <button 
      class="select-member-btn" 
      @click="showMemberList"
      :disabled="disabled"
    >
      <text v-if="selectedMember">
        {{ selectedMember.nickname || '未知用户' }}
      </text>
      <text v-else>选择队员</text>
    </button>

    <!-- 队员列表弹窗 -->
    <view v-if="showList" class="member-list-modal">
      <view class="modal-header">
        <text class="modal-title">选择队员</text>
        <button class="close-btn" @click="closeModal">×</button>
      </view>
      
      <!-- 搜索框 -->
      <view class="search-container">
        <input 
          class="search-input" 
          v-model="searchKeyword" 
          placeholder="搜索队员..."
          @input="onSearch"
        />
      </view>
      
      <!-- 队员列表 -->
      <scroll-view class="member-list" scroll-y>
        <view v-if="loading" class="loading">
          <text>加载中...</text>
        </view>
        
        <view v-else-if="filteredMembers.length" class="members-container">
          <view 
            v-for="member in filteredMembers" 
            :key="member.userId" 
            class="member-item"
            @click="selectMember(member)"
          >
            <image 
              :src="getAvatarUrl(member.avatarUrl)" 
              class="member-avatar" 
              @error="handleAvatarError" 
            />
            <view class="member-info">
              <text class="member-name">{{ member.nickname }}</text>
              <text class="member-role">{{ member.role === 'leader' ? '队长' : '队员' }}</text>
            </view>
            <view v-if="selectedMember && selectedMember.userId === member.userId" class="selected-indicator">
              ✓
            </view>
          </view>
        </view>
        
        <view v-else class="empty-state">
          <text class="empty-text">暂无队员</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { getAvatarUrl } from '@/utils/imageUtils.js'

const props = defineProps({
  disabled: {
    type: Boolean,
    default: false
  },
  currentUserId: {
    type: [String, Number],
    required: true
  },
  teamMembers: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['select', 'clear'])

// 数据
const showList = ref(false)
const members = ref([])
const loading = ref(false)
const searchKeyword = ref('')
const selectedMember = ref(null)

// 计算属性
const filteredMembers = computed(() => {
  return members.value.filter(member => {
    const name = member.nickname || ''
    return name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  })
})

// 方法
const showMemberList = () => {
  if (props.disabled) return
  showList.value = true
  loadMembers()
}

const closeModal = () => {
  showList.value = false
  searchKeyword.value = ''
}

const selectMember = (member) => {
  selectedMember.value = member
  emit('select', member)
  closeModal()
}

const clearSelection = () => {
  selectedMember.value = null
  emit('clear')
}

const loadMembers = async () => {
  loading.value = true
  try {
    // 直接使用传入的团队成员数据
    members.value = props.teamMembers || []
  } catch (error) {
    console.error('加载队员列表失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

const onSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleAvatarError = (e) => {
  console.log('头像加载失败:', e)
}

// 暴露方法给父组件
defineExpose({
  clearSelection,
  setSelectedMember: (member) => {
    selectedMember.value = member
  }
})
</script>

<style scoped>
.team-member-selector {
  position: relative;
}

.select-member-btn {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  background: #fff;
  text-align: left;
  font-size: 14px;
  color: #333;
}

.select-member-btn:disabled {
  background: #f5f5f5;
  color: #999;
}

.member-list-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #fff;
  border-bottom: 1px solid #eee;
}

.modal-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.close-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: #f5f5f5;
  border-radius: 50%;
  font-size: 20px;
  color: #666;
}

.search-container {
  padding: 16px;
  background: #fff;
  border-bottom: 1px solid #eee;
}

.search-input {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
}

.member-list {
  flex: 1;
  background: #fff;
}

.members-container {
  padding: 0 16px;
}

.member-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
  position: relative;
}

.member-item:last-child {
  border-bottom: none;
}

.member-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 12px;
  object-fit: cover;
}

.member-info {
  flex: 1;
}

.member-name {
  display: block;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 2px;
}

.member-role {
  font-size: 12px;
  color: #999;
}

.selected-indicator {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
  color: #4CAF50;
  font-size: 18px;
  font-weight: bold;
}

.loading {
  text-align: center;
  padding: 20px;
  color: #999;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.empty-text {
  color: #999;
  font-size: 14px;
}
</style>
